(function(global,factory){
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global = global || self, global.createCoord = factory());
}(this, function(){
    // 建立坐标
    return function createCoord(target) {
        const { left: targetLeft, top: targetTop, width: targetWidth, height: targetHeight } = target.getBoundingClientRect();
        function coordContext(el) {
            const {scaleX, skewY, skewX, scaleY, translateX, translateY } = coordContext.getTransform(el);
            const { left: elLeft, top: elTop, width: elWidth, height: elHeight } = el.getBoundingClientRect();
            // el元素距离target元素的left距离
            let left = (elLeft + elWidth/2) - (targetLeft + targetWidth/2);
            let top = -1 * ((elTop + elHeight/2) - (targetTop + targetHeight/2));
            const coordIns = {
                // 设置一个相对target元素的坐标
                setCoord(coord = {x: 0, y: 0}) {
                    const {x: realX, y: realY} = coordIns.toRealCoord(coord);
                    el.style.setProperty('transform', `matrix(${scaleX}, ${skewY}, ${skewX}, ${scaleY}, ${realX}, ${realY})`);
                    return this;
                },
                // 获取相对target坐标的位置信息
                getCoord() {
                    return {x: left, y: top }
                },
                // 相对坐标=>转真实坐标
                toRealCoord(coord) {
                    return { x: -left + coord.x + translateX, y: top - coord.y + translateY }
                }
            }
            return coordIns; 
        }

        // 重置transform的值
        coordContext.getTransform = (el) => {
            const matrix = getComputedStyle(el)['transform'];
            let matrixArr = [1,0,0,1,0,0];
            if(matrix !== 'none') {
                matrixArr = matrix.slice(matrix.indexOf('(')+1, matrix.indexOf(')')).split(',').map(item => parseFloat(item));
            }
            return {
                scaleX: matrixArr[0],
                skewY: matrixArr[1],
                skewX: matrixArr[2],
                scaleY: matrixArr[3],
                translateX: matrixArr[4],
                translateY: matrixArr[5]
            };
        }
        
        // 鼠标的实时坐标
        coordContext.mouseCoord = (callback) => {
            document.addEventListener('mousemove', (e) => {
                const left = (e.clientX - (targetLeft + targetWidth/2));
                const top = -1 * (e.clientY - (targetTop + targetHeight/2));
                callback({x: left, y: top});
            });
        }
        
        return coordContext;
    }
}));